#!/use/bin/python
# coding=utf-8
# 主动服务-每周服务次数 analysis_service_number
import datetime
import pymysql
from dateutil.relativedelta import relativedelta

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur


#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql):
    conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    if num is None:
        return 0
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if(X is None or Y is None):
        return rate
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X / Y, 4) * 100
    return rate

# 记录 数据分析-主动服务-开机数-同比/环比  analysis_service_number   服务次数  每天
def insertServiceNumberDay(date):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_startup_rate 表是否已经存在当天 开机率数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_service_number t where 1=1 and t.ref_date =  '{date}' and dateType = 1")
        # 获取早间服务执行次数
        zjkjNum = selectNumBySql(
            f"select count(1)from log_common_service_{yyMMddDate} t where t.`key` = 'openScreen'")
        # 获取 追剧提醒服务次数
        zjtxNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.`key` = 'suAutoOpenScreen'  ")
        # 获取 健康作息服务次数
        jkzxNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.`key` = 'hlTipShow'  ")
        # 获取 夜间音量服务次数
        yjylNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.`key` = 'narvExecute'  ")
        # 获取 睡觉提醒服务次数
        sjtxNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.`key` = 'srShowResult' and JSON_EXTRACT(msg,'$.result') =1 ")
        # 获取 助眠功能服务次数
        zmgnNum = selectNumBySql(
            f"select count(1) from log_common_service_{yyMMddDate} t where t.`key` = 'saEnterPage' ")
        # 计算因生活助手服务次数
        serviceNum = zjkjNum + zjtxNum+jkzxNum+yjylNum+sjtxNum+zmgnNum;

        if countNum == 0:
            logDetail = f"新增-{date}日-生活助手服务次数,早间服务次数为{zjkjNum},追剧提醒服务次数为{zjtxNum},健康作息服务次数为{jkzxNum},夜间音量服务次数为{yjylNum},睡觉提醒服务次数为{sjtxNum},助眠功能服务次数为{zmgnNum},总服务次数为{serviceNum}"
            print(logDetail)
            # 插入
            insertSql = f"""insert into analysis_service_number(service_num,ref_date,dateType) 
                value({serviceNum},'{date}',1)"""
            cur.execute(insertSql)
        else:
            logDetail = f"新增-{date}日-生活助手服务次数,早间服务次数为{zjkjNum},追剧提醒服务次数为{zjtxNum},健康作息服务次数为{jkzxNum},夜间音量服务次数为{yjylNum},睡觉提醒服务次数为{sjtxNum},助眠功能服务次数为{zmgnNum},总服务次数为{serviceNum}"
            print(logDetail)
            # 更新
            updateSql = f"""
                update analysis_service_number set service_num = {serviceNum} ,update_time = now()  where  ref_date = '{date}' and dateType = 1
            """
            cur.execute(updateSql)
        saveLog(logDetail, date)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 记录 数据分析-主动服务-服务次数比  analysis_service_number   服务次数 -月度
# toMonthDay 当月 beforeMonthDay 上一个月 beforeYearDay 去年同一月 type 1订阅数 2订阅设备量
def insertServiceNumberMonth(toMonthDay,beforeMonthDay,beforeYearDay):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_service_rate 表是否已经存在当月数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_service_number t where 1=1 and t.ref_date =  '{toMonthDay}' and dateType = 3")
        # 获取 月度生活助手服务次数
        serviceNum = selectNumBySql(
            f"select sum(service_num) from analysis_service_number t  where 1=1 and SUBSTR(t.ref_date, 1, 7) = '{toMonthDay}' and LENGTH(t.ref_date) = 10 and dateType = 1")

        bmAllNum = selectNumBySql(
            f"select service_num from analysis_service_number t  where  t.ref_date = '{beforeMonthDay}' and dateType = 3")
        #上一个年相同月份 计算同比
        byAllNum = selectNumBySql(
            f"select service_num from analysis_service_number t  where  t.ref_date = '{beforeYearDay}' and dateType = 3")
        # 计算服务次数及同比环比
        monthOnMonthService = getRateByXY(serviceNum-bmAllNum,bmAllNum)
        yearOnYearService = getRateByXY(serviceNum-byAllNum,byAllNum)

        if countNum == 0:
            logDetail = f"新增-{toMonthDay}月-服务次数,月总服务次数为{serviceNum},去年当月服务次数为{byAllNum},环比为{yearOnYearService},生活助手上月服务次数为{bmAllNum},同比为{monthOnMonthService}"
            print(logDetail)
            # 插入
            insertSql = f"""insert into analysis_service_number(service_num,year_on_year,month_on_month,ref_date,dateType) 
                            value({serviceNum},{yearOnYearService},{monthOnMonthService},'{toMonthDay}',3)"""
            cur.execute(insertSql)
        else:
            logDetail = f"修改-{toMonthDay}月-服务次数,月总服务次数为{serviceNum},去年当月服务次数为{byAllNum},环比为{yearOnYearService},生活助手上月服务次数为{bmAllNum},同比为{monthOnMonthService}"
            print(logDetail)
            # 更新
            updateSql = f"""
                update analysis_service_number set service_num = {serviceNum} ,
                year_on_year = {yearOnYearService},month_on_month = {monthOnMonthService},update_time = now()  where ref_date = '{toMonthDay}'  and dateType = 3
            """
            cur.execute(updateSql)
        saveLog(logDetail, toMonthDay)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 记录 数据分析-主动服务-服务次数 analysis_service_number   开机次数 -周
def insertServiceNumberWeek(toDay):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_startup_rate 表是否已经存在当天 开机率数据
        countNum = selectNumBySql(
            f"select count(1) num from analysis_service_number t where 1=1 and weekofyear(t.ref_date) = weekofyear('{toDay}')  and dateType = 2 ")
        # 获取 当周生活助手服务次数
        serviceNum = selectNumBySql(
            f"""select sum(t.service_num) from analysis_service_number t where t.dateType = 1 and LENGTH(t.ref_date) = 10 
                                      and weekofyear(t.ref_date) = weekofyear('{toDay}') """)

        # 获取 上一周周因生活助手开机次数 计算环比
        bmServiceNum = selectNumBySql(
            f"""
                    select t.service_num from analysis_service_number t where t.dateType = 2 
                        and weekofyear(t.ref_date) = weekofyear('{toDay}') -1 """)
        # 上一个年相同周 因生活助手开机次数 计算同比
        byServiceNum = selectNumBySql(
            f"""
                            select t.service_num from analysis_service_number t where t.dateType = 2  
                                and weekofyear(t.ref_date) = weekofyear('{toDay}') and year(t.ref_date) =  year('{toDay}') - 1""")
        # 计算因主动服务 开机设备数及同比环比
        monthOnMonthService = getRateByXY(serviceNum - bmServiceNum, bmServiceNum)
        yearOnYearService = getRateByXY(serviceNum - byServiceNum, byServiceNum)



        if countNum == 0:
            logDetail = f"新增-{toDay}周-服务次数,周总服务次数为{serviceNum},去年当周服务次数为{byServiceNum},环比为{yearOnYearService},生活助手上周服务次数为{bmServiceNum},同比为{monthOnMonthService}"
            print(logDetail)
            # 插入
            insertSql = f"""insert into analysis_service_number(service_num,year_on_year,month_on_month,ref_date,dateType) 
                            value({serviceNum},{yearOnYearService},{monthOnMonthService},'{toDay}',2)"""
            cur.execute(insertSql)
        else:
            logDetail = f"修改-{toDay}周-服务次数,周总服务次数为{serviceNum},去年当周服务次数为{byServiceNum},环比为{yearOnYearService},生活助手上周服务次数为{bmServiceNum},同比为{monthOnMonthService}"
            print(logDetail)
            # 更新
            updateSql = f"""
                update analysis_service_number set service_num = {serviceNum} ,
                year_on_year = {yearOnYearService},month_on_month = {monthOnMonthService},update_time = now(),ref_date = '{toDay}'  where weekofyear(ref_date) = weekofyear('{toDay}')  and dateType = 2
            """
            cur.execute(updateSql)
        saveLog(logDetail, toDay)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

# 获取上一个月
def getBeforeMonth(d):
    today = datetime.datetime.now()
    re_date = (today + relativedelta(months=-d)).strftime("%Y-%m")
    return re_date

# 获取上一个年当月
def getBeforeYear():
    today = datetime.datetime.now()
    re_date = (today + relativedelta(years=-1)).strftime("%Y-%m")
    return re_date

#如 2022年12月13号 获取 221213 作为分表后缀
def getdateyyMMdd(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    re_date = re_date[2:]
    return re_date

def saveLog(detail,ref_date):
    try:
        conn, cur = getDataConnection()
        jobId = 52
        jobName = '核心指标-生活助手-服务次数	'
        tableName = 'analysis_service_number'
        # 插入日志表
        saveLogSql = """insert into log_xxljob_analysis (job_id,job_name,detail,table_name,ref_date) 
                value(%s,'%s','%s','%s','%s')""" % (jobId,jobName,detail,tableName,ref_date)
        cur.execute(saveLogSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    d = 1
    today = getdate(d)
    yyMMddDate = getdateyyMMdd(d)
    toMonthDay = getMonthdate(d)
    beforeMonthDay = getBeforeMonth(1)
    beforeYearDay = getBeforeYear()
    print(f"{today}日期,执行<生活助手服务次数>报表")
    insertServiceNumberDay(today,)
    insertServiceNumberMonth(toMonthDay, beforeMonthDay, beforeYearDay)
    insertServiceNumberWeek(today)


